package com.sf.template.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 埔枘
 * @date 2019/12/02
 **/
public abstract class JdbcTemplate<T> {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public List<T> executeQuery(String sql,RowMapper<?> reow,Object[] objects){
        try{
            //1.获得链接
            Connection connection = this.dataSource.getConnection();
            //2.创建语句集
            PreparedStatement prepareStatement = this.createPrepareStatement(connection, sql);
            //3.执行
            ResultSet resultSet = this.execute(prepareStatement,objects);
            //4.处理返沪结果
            List list = this.handlerResult(resultSet,reow);
            //5.关闭相关资源
            this.closeResource(connection,prepareStatement,resultSet);
        }catch (Exception e){

        }
        return null;
    }

    protected void closeResource(Connection connection, PreparedStatement prepareStatement, ResultSet resultSet) throws SQLException {
        resultSet.close();
        prepareStatement.clearParameters();
        connection.close();
    }

    protected List handlerResult(ResultSet resultSet, RowMapper<?> reow) throws Exception {
        List<Object> result = new ArrayList<Object>();
        int rowNum = 1;
        while (resultSet.next()){
            result.add(reow.mapRow(resultSet,rowNum ++));
        }
        return result;
    }

    protected ResultSet execute(PreparedStatement prepareStatement, Object[] objects) throws SQLException {
        for(int i=0;i<objects.length;i++){
            prepareStatement.setObject(i,objects[i]);
        }
        return prepareStatement.executeQuery();
    }

    PreparedStatement createPrepareStatement(Connection connection, String sql) throws Exception {
        return connection.prepareStatement(sql);
    }

}
